home *** CD-ROM | disk | FTP | other *** search
- Path: gate.net!pslfl2-10
- From: bhutto@gate.net (William Hutto)
- Newsgroups: comp.lang.c
- Subject: Re: Packing characters
- Date: 8 Jan 1996 11:21:01 GMT
- Organization: CyberGate, Inc.
- Message-ID: <4cqumt$1quo@news.gate.net>
- References: <4cp6st$phk@news.isc.rit.edu> <30F0EFB1.AD3@cnsunix.albany.edu>
- NNTP-Posting-Host: pslfl2-10.gate.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- In article <30F0EFB1.AD3@cnsunix.albany.edu>,
- Nicholas Paldino <np1010@cnsunix.albany.edu> wrote:
- >SWANSON wrote:
- >>
- >> Problem: I have a value like this: XXX.YYY where the X and Y's
- >> are numbers, like in an ip address. The values are 0-255.
- >>
- >> What is the best way to store them so they take up the least
- >> amount of room? Later I need to traansmit them in a packet
- >> header, so space is an issue.
- >>
- >> Thanks,
- >>
- >> Carl
- >> css0958@grace.rit.edu
- >
- >This is my first time posting here and I have only six months experience
- >with C but I believe that you could store those values in an unsigned
- >char (assuming that a char on your machine uses 8 bits). Four of those
- >in turn could be packed into an int (using masking and whatnot and
- >assuming that an int is four bytes on your machine). Good luck.
- >
- > - Nicholas Paldino
- > - np1010@cnsunix.albany.edu
-
- It sounds like you need to use the ol' union. Given an example.
-
- typedef union {
- unsigned char route[2];
- unsigned short address;
- }IP;
-
- func()
- {
- IP ip;
-
- ip.route[0]=getbyte();
- ip.route[1]=getbyte();
- do_something_with(ip.address);
- }
-
- The union virtually allows more than one data item to occupy the same space.
- I illustrate:
-
-
- ip.<item>
- ------------------------------------------
- | | |
- | | |
- | address |
- | | |
- | route[0] | route[1] |
- | | |
- ------------------------------------------
-
- In this example:
- ip.address refers to the whole which is of size unsigned short int.
- ip.route[0] refers to the low byte of the whole.
- ip.route[1] refers to the high byte of the whole.
-
-
- For a full ip address you could use:
-
- typedef union {
- unsigned char route[4];
- unsigned long address;
- }IP;
-
- Which allows you to break ip.address into 4 individual parts:
- ip.route[0]
- ip.route[1]
- ...
-
- The only problem you might have with unions is the dependence of sizeof(type).
- In order for the alignment of these cohabitant objects to be useful, they need
- to be a predecribed size. You may want to include some checking in your code
- to make sure the union elements align properly.
-
- I hope that gives you some direction.
-
- Bill
-
-
- "Whatcha got on?...Your mind?"
-